#ifndef __CONTROLLER_3D_H__
#define __CONTROLLER_3D_H__

#include "controller.h"
#include "view/perspective_view.h"
#include "model/perspective_model.h"

class Controller3D : public Controller{
	private:
		Point dragPos;
		bool drag;
	public:
		Controller3D(View* view,Model* model)
			: Controller(view,model),dragPos(0,0){
			this->drag=false;
		}

		~Controller3D(){}

		void display() {
			this->view->display();
		}

		void mouseMotion(float x ,float y){
			PerspectiveView& pview = dynamic_cast<PerspectiveView&>(*this->view);
			if(drag){
				Point dragDir = dragPos - Point(x,y);

				// Normalizar
				if(fabs(dragDir.x1)>0 && fabs(dragDir.x2)>0)
					dragDir = Point(dragDir.x1/fabs(dragDir.x1),dragDir.x2/fabs(dragDir.x2));
				else if(fabs(dragDir.x1)>0)
					dragDir = Point(dragDir.x1/fabs(dragDir.x1),0);
				else if(fabs(dragDir.x2)>0)
					dragDir = Point(0,dragDir.x2/fabs(dragDir.x2));

				pview.getCamera().rotateLR(-dragDir.x1*1.3f);
				pview.getCamera().rotateUD(-dragDir.x2*1.3f);

				dragPos = Point(x,y);
			}

		}

		void reshape(float w,float h) {
			this->view->reshape(w,h);
		}

		void mousePressed(int key,int state,float x ,float y){
			if(key==GLUT_LEFT_BUTTON && state==GLUT_DOWN){
				dragPos = Point(x,y);
				drag=true;
			}
			if(key==GLUT_LEFT_BUTTON && state==GLUT_UP)
				drag=false;
		}

		void keyboard(unsigned char key,float x ,float y){
			PerspectiveView& pview = dynamic_cast<PerspectiveView&>(*this->view);
			switch(key){
				case 'w':
					pview.getCamera().move(-0.05f);
					break;
				case 's':
					pview.getCamera().move(0.05f);
					break;
				case 'a':
					pview.getCamera().rotateLR(-1.5f);
					break;
				case 'd':
					pview.getCamera().rotateLR(1.5f);
					break;
				case 'q':
					pview.getCamera().rotateUD(1.5f);
					break;
				case 'e':
					pview.getCamera().rotateUD(-1.5f);
					break;
				case 'b':
					dynamic_cast<PerspectiveModel&>(*model).calculate();
					break;
			}
		}

		void notifyViewportLeave(){}
};

#endif //__CONTROLLER_3D__H__
